package com.mojo.jvm.jvm_03_heap;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

/**
 * @author <a href="mailto:sjj@jianzhimao.com">mojo</a>
 * copyright (C), 2013-2022, 广州九尾信息科技有限公司
 * @date 2022/10/19 11:20
 */
public class HeapDemo {
    public static void main(String[] args) {

        //返回 JVM 堆大小
        long freeMemory = Runtime.getRuntime().freeMemory() / 1024 / 1024;
        long initalMemory = Runtime.getRuntime().totalMemory() / 1024 / 1024;
        //返回 JVM 堆的最大内存
        long maxMemory = Runtime.getRuntime().maxMemory() / 1024 / 1024;
        System.out.println("-空闲内存 : " + freeMemory + "M");
        System.out.println("-Xms : " + initalMemory + "M");
        System.out.println("-Xmx : " + maxMemory + "M");

        System.out.println("系统内存大小：" + initalMemory * 64 / 1024 + "G");
        System.out.println("系统内存大小：" + maxMemory * 4 / 1024 + "G");
        for (String arg : args) {
            System.out.println(">>>" + arg);
        }
        //heapOom();
        fullGc();
    }

    //频繁fullGc示例,OutOfMemoryError: GC overhead limit exceeded
    private static void fullGc() {
        ArrayList<Map> list = new ArrayList<>();
        for (int i = 0; i < 20000; i++) {
            HashMap<Object, Object> map = new HashMap<>();
            try {
                Thread.sleep(10L);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            for (int j = 0; j < i; j++) {
                map.put(j, i);
            }
            System.out.println("=============================================");
            System.out.println(">>>>>外循环次数>>>>" + i);
            list.add(map);
        }
    }

    //对内存溢出示例，OutOfMemoryError: Java heap space
    public static void heapOom() {
        ArrayList<Object> list = new ArrayList<>(10);
        while (true) {
            list.add(1);
        }

    }

}
